#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include "config.h"

// 安全的字符串复制
static void safe_strcpy(char* dest, const char* src, size_t dest_size) {
    if (dest_size == 0) return;
    
    size_t src_len = strlen(src);
    size_t copy_len = (src_len < dest_size - 1) ? src_len : dest_size - 1;
    
    if (copy_len > 0) {
        memcpy(dest, src, copy_len);
    }
    dest[copy_len] = '\0';
}

// 安全的JSON值提取
static bool extract_json_value(const char* line, const char* key, char* value, size_t value_size) {
    char search_pattern[64];
    snprintf(search_pattern, sizeof(search_pattern), "\"%s\"", key);
    
    const char* pos = strstr(line, search_pattern);
    if (!pos) return false;
    
    pos = strchr(pos, ':');
    if (!pos) return false;
    pos++;
    
    // 跳过空格
    while (*pos && isspace(*pos)) pos++;
    
    if (*pos == '"') {
        // 字符串值
        pos++;
        const char* end = strchr(pos, '"');
        if (!end) return false;
        
        size_t len = end - pos;
        if (len >= value_size) len = value_size - 1;
        
        strncpy(value, pos, len);
        value[len] = '\0';
    } else {
        // 数字值
        const char* end = pos;
        while (*end && (isdigit(*end) || *end == '-' || *end == '.')) end++;
        
        size_t len = end - pos;
        if (len >= value_size) len = value_size - 1;
        
        strncpy(value, pos, len);
        value[len] = '\0';
    }
    
    return true;
}

int load_config(const char* filename, config_t* config) {
    FILE* file = fopen(filename, "r");
    if (!file) {
        fprintf(stderr, "Error: Cannot open config file %s: %s\n", filename, strerror(errno));
        return -1;
    }

    // 设置默认值
    memset(config, 0, sizeof(config_t));

    config->polling_interval_ms = 1;
    config->test_duration.duration_hours = 0;
    config->test_duration.duration_minutes = 0;
    config->test_duration.duration_seconds = 30;
    config->input_register_range.start_address = 0;
    config->input_register_range.end_address = 1000;
    config->holding_register_range.start_address = 0;
    config->holding_register_range.end_address = 2000; 

    for(int i=0;i<4;i++){
        safe_strcpy(config->modbus_servers[i].ip,"127.0.0.1",MAX_IP_LENGTH);
        config->modbus_servers[i].port = 502;
        config->modbus_servers[i].slave_id = 1;
        config->modbus_servers[i].disable_nagle = true;

        // config->rt_config.process_cpu_core = 8;
        config->rt_configs[i].thread_cpu_core = 8;  // 默认与进程不同核心
        // config->rt_config.process_priority = -20; // 最高优先级
        config->rt_configs[i].thread_priority = 80;   // 实时线程优先级
        config->rt_configs[i].lock_memory = true;
        config->rt_configs[i].tcp_send_buffer_size = TCP_BUFFER_SIZE;
        config->rt_configs[i].tcp_recv_buffer_size = TCP_BUFFER_SIZE;
        config->rt_configs[i].disable_tcp_delay_ack = true;
    }

    char line[512];
    char value[256];
    int current_server_index = -1;
    int current_rt_config_index = -1;
    
    while (fgets(line, sizeof(line), file)) {
        // 移除换行符和空格
        line[strcspn(line, "\n")] = 0;
        char* trimmed = line;
        while (*trimmed && isspace(*trimmed)) trimmed++;
        
        if (strlen(trimmed) == 0 || trimmed[0] == '/') continue;

                // 检查是否进入服务器配置数组
        if (strstr(trimmed, "\"modbus_server\": [")) {
            current_server_index = 0;
            continue;
        }
        
        // 检查是否进入实时配置数组
        if (strstr(trimmed, "\"rt_config\": [")) {
            current_rt_config_index = 0;
            continue;
        }

        if (extract_json_value(trimmed, "polling_interval_ms", value, sizeof(value))) {
            config->polling_interval_ms = (uint32_t)atoi(value);
        } else if (extract_json_value(trimmed, "duration_hours", value, sizeof(value))) {
            config->test_duration.duration_hours = (uint32_t)atoi(value);
        } else if (extract_json_value(trimmed, "duration_minutes", value, sizeof(value))) {
            config->test_duration.duration_minutes = (uint32_t)atoi(value);
        } else if (extract_json_value(trimmed, "duration_seconds", value, sizeof(value))) {
            config->test_duration.duration_seconds = (uint32_t)atoi(value);
        }else if (extract_json_value(trimmed, "start_address", value, sizeof(value))) {
            // 需要上下文判断是input还是holding
            if (strstr(trimmed, "input_register_range")) {
                config->input_register_range.start_address = (uint32_t)atoi(value);
            } else if (strstr(trimmed, "holding_register_range")) {
                config->holding_register_range.start_address = (uint32_t)atoi(value);
            }
        } else if (extract_json_value(trimmed, "end_address", value, sizeof(value))) {
            if (strstr(trimmed, "input_register_range")) {
                config->input_register_range.end_address = (uint32_t)atoi(value);
            } else if (strstr(trimmed, "holding_register_range")) {
                config->holding_register_range.end_address = (uint32_t)atoi(value);
            }
        } else if (current_server_index >= 0 && current_server_index < 4) {
            // 处理服务器配置
            if (extract_json_value(trimmed, "ip", value, sizeof(value))) {
                safe_strcpy(config->modbus_servers[current_server_index].ip, value, MAX_IP_LENGTH);
            } else if (extract_json_value(trimmed, "port", value, sizeof(value))) {
                config->modbus_servers[current_server_index].port = (uint32_t)atoi(value);
            } else if (extract_json_value(trimmed, "slave_id", value, sizeof(value))) {
                config->modbus_servers[current_server_index].slave_id = (uint32_t)atoi(value);
            } else if (extract_json_value(trimmed, "disable_nagle", value, sizeof(value))) {
                config->modbus_servers[current_server_index].disable_nagle = 
                    (strcasecmp(value, "true") == 0 || atoi(value) != 0);
            } else if (strstr(trimmed, "},") || strstr(trimmed, "}")) {
                // 服务器配置结束，移动到下一个
                current_server_index++;
            }
        } 
        else if (current_rt_config_index >= 0 && current_rt_config_index < 4) {
            // 处理实时配置
            if (extract_json_value(trimmed, "thread_cpu_core", value, sizeof(value))) {
                config->rt_configs[current_rt_config_index].thread_cpu_core = (uint32_t)atoi(value);
            } else if (extract_json_value(trimmed, "thread_priority", value, sizeof(value))) {
                config->rt_configs[current_rt_config_index].thread_priority = (int32_t)atoi(value);
            } else if (extract_json_value(trimmed, "lock_memory", value, sizeof(value))) {
                config->rt_configs[current_rt_config_index].lock_memory = 
                    (strcasecmp(value, "true") == 0 || atoi(value) != 0);
            } else if (extract_json_value(trimmed, "tcp_send_buffer_size", value, sizeof(value))) {
                config->rt_configs[current_rt_config_index].tcp_send_buffer_size = (uint32_t)atoi(value);
            } else if (extract_json_value(trimmed, "tcp_recv_buffer_size", value, sizeof(value))) {
                config->rt_configs[current_rt_config_index].tcp_recv_buffer_size = (uint32_t)atoi(value);
            } else if (extract_json_value(trimmed, "disable_tcp_delay_ack", value, sizeof(value))) {
                config->rt_configs[current_rt_config_index].disable_tcp_delay_ack = 
                    (strcasecmp(value, "true") == 0 || atoi(value) != 0);
            } else if (strstr(trimmed, "},") || strstr(trimmed, "}")) {
                // 实时配置结束，移动到下一个
                current_rt_config_index++;
            }
        }
    }

    fclose(file);
    return 0;
}
